
#include <serpent.h>
#include "serpentd_props.h"

bool prop_add(obj_t* o, str name, str value) {
	prop e;
	prop new;

	if( prop_exists(o,name) )
		return(false);

	if( o->props != NULL ) // if list is already present
	{
		e = o->props;

		while( e->next != NULL )
		{
			e = e->next;
		}

		new = (prop)calloc(1,sizeof(s_property_t));
		if( new == NULL )
			return(false);

		new->name = (char*)calloc(1,sizeof(name));
		new->value = (char*)calloc(1,sizeof(value));

		strcat(new->name,name);
		strcat(new->value,value);
		e->next = new;
	}
	else // if no list is present -> create a new list out of one element
	{
		new = (prop)calloc(1,sizeof(s_property_t));
		if( new == NULL )
			return(false);

		new->name = (char*)calloc(1,sizeof(name));
		new->value = (char*)calloc(1,sizeof(value));

		strcat(new->name,name);
		strcat(new->value,value);
		o->props = new;
	}

	return(true);
}

bool prop_del(obj_t* o, str name) {
	prop left = NULL;
	prop p = NULL;
	prop temp = NULL;

	if( o->props == NULL )
		return(false);

	if( !prop_exists(o,name) )
		return(false);

	p = o->props;

	for(;;)
	{
		if( 0 == strcmp(name,p->name) )
		{ // if element is found
			if(left != NULL && p != NULL)
			{ // element is next to elements
				temp = p->next;
				s_free(p);
				left->next = temp;
				temp = NULL;
				return(true);
			}
			else if( left == NULL && p != NULL )
			{ // element has no parent, but childs
				temp = p->next;
				s_free(p);
				o->props = temp;
				temp = NULL;
				return(true);
			}
			else if( left != NULL && p == NULL )
			{ // element has no child, but parents
				s_free(p);
				left->next = NULL;
				return(true);
			}
			return(false);
		}

		left = p;
		p = p->next;
		if( p == NULL )
		{
			break;
		}
	}

	return(false);
}

str prop_get(obj_t* o,str name) {
	prop p;

	if( NULL == o )
	{
		return(NULL);
	}

	if( NULL == o->props )
	{
		return(NULL);
	}

	p = o->props;

	while( p->next != NULL || p->name != NULL ) //
		// There must be some cleaner or easier way. patches?
	{
		if( 0 == strcmp(p->name,name) )
		{
			return(p->value);
		}

		if(p->next != NULL)
		{
			p = p->next;
		}
		else
		{
			break;
		}
	}

	return(NULL);
}

bool prop_set(obj_t* o, str name, str value)
{
	if( o->props == NULL )
		return(false);

	if( !prop_exists(o,name) )
		return(false);

	if( !prop_del(o,name) )
		return(false);

	if( !prop_add(o,name,value) )
		return(false);

	return(true);
}

bool props_destroy(obj_t* o) {
	prop e;
	prop kill;

	if( o->props == NULL ) // if list is already empty, return
		return(false);

	e = o->props;
	while( e->next != NULL )
	{
		kill = e;
		e = e->next;

		if( kill->name != NULL )
			s_free(kill->name);

		if( kill->value != NULL )
			s_free(kill->value);

		s_free(kill);
	}

	o->props = NULL;
	return(true);
}

bool prop_exists(obj_t* o, str name) {
	str n = prop_get(o,name);

	if( n == NULL )
	{
		return(false);
	}
	else
	{
		return(true);
	}
}
